<template>
  <!-- 维护作业-银保通出单保费限额维护页面 -->
  <div class="fillcontain">
    <el-form :model="searchParams" :rules="rules" ref="ruleForm" label-width="100px" class="search_container">
      <el-row>
        <el-col :span="6">
          <el-form-item label="分公司" prop="chdrcoy">
            <el-select v-model="searchParams.chdrcoy" placeholder="" @change="getBranchOptions" clearable>
              <el-option v-for="item in chdrcoyOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="分支机构" prop="branch">
            <el-select v-model="searchParams.branch" placeholder="" clearable>
              <el-option v-for="item in branchOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="银行名称" prop="bankName">
            <el-input clearable v-model="searchParams.bankName" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" class="text_center">
          <el-button type="primary" icon="el-icon-search" @click="subGetList"></el-button>
          <el-button type="primary" plain icon="el-icon-refresh" @click="resetSearch"></el-button>
        </el-col>
      </el-row>
    </el-form>
    <div class="contain">
      <el-row class="bgfff pb15">
        <el-col :span="24" class="pt5">
          <el-button type="danger" @click="toAddDialog" plain>新增</el-button>
          <el-button type="danger" @click="exportData" plain>导出</el-button>
        </el-col>
      </el-row>
      <!-- 查询结果 -->
      <div class="table_container">
        <el-table v-loading="loading" :data=" tableData" highlight-current-row
                  header-cell-class-name="table-header-class" style="width:100%">
          <el-table-column min-width="120" property="chdrcoy" :formatter="chdrcoyFormat" label="分公司" align='center'
                           show-overflow-tooltip>
          </el-table-column>
          <el-table-column min-width="120" property="branch" :formatter="branchFormat" label="分支机构" align='center'
                           show-overflow-tooltip>
          </el-table-column>
          <el-table-column min-width="120" property="bankName" label="银行名称" align='center' show-overflow-tooltip>
          </el-table-column>
          <el-table-column min-width="120" property="maxPremium" label="最高保额" align='center' show-overflow-tooltip>
          </el-table-column>
          <el-table-column fixed="right" label="操作" align='center'>
            <template slot-scope="scope">
              <!-- <el-button type="text" size="small" @click="toEditDialog(scope.row)">修改</el-button> -->
              <span class="operationIcon" @click="toEditDialog(scope.row)">
                <el-tooltip class="item" effect="light" content="修改" placement="top">
                  <i class="el-icon-edit"></i>
                </el-tooltip>
              </span>
              <!-- <el-button type="text" size="small" @click="deleteData(scope.row)">删除</el-button> -->
              <span class="operationIcon ml5" @click="deleteData(scope.row)">
                <el-tooltip class="item" effect="light" content="删除" placement="top">
                  <i class="el-icon-delete"></i>
                </el-tooltip>
              </span>

            </template>
          </el-table-column>
        </el-table>
        <el-row>
          <el-col :span="24">
            <div class="pagination">
              <el-pagination background v-if='paginations.total > 0' :page-sizes="paginations.pageSizes"
                             :page-size="paginations.pageSize"
                             :layout="paginations.layout" :total="paginations.total"
                             :current-page='paginations.pageIndex' @current-change='handleCurrentChange'
                             @size-change='handleSizeChange'>
              </el-pagination>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <!-- 弹框 修改-->
    <el-dialog :title="title_O" :visible.sync="bankPremiumslimitDialog" width="60%" center>
      <el-form ref="oneDataForm" :model="oneData" :rules="oneDataRules" label-width="130px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="分公司" prop="chdrcoy">
              <el-select v-model="oneData.chdrcoy" placeholder="" @change="getBranchOptions_D">
                <el-option v-for="item in chdrcoyOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分支机构" prop="branch">
              <el-select v-model="oneData.branch" placeholder="">
                <el-option v-for="item in branchOptions_D" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行名称" prop="bankName">
              <el-input v-model="oneData.bankName" clearable placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最高保费" prop="maxPremium">
              <el-input v-model="oneData.maxPremium" clearable placeholder=""></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="saveData" class="Defaultbutton">保 存</el-button>
        <el-button @click="dialogBack">返 回</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import {mapState, mapGetters} from 'vuex'
  import constant from '@/utils/constant';
  import {ADD, DELETE, PAGE, UPDATE, queryListToExcel} from "@/api/setting/maintain/bankPremiumslimitMaintenance";
  import {getSsyOrgMap} from "@/api/taskCenter/taskCommon";
  import validRules from "@/utils/validRules";

  export default {
    data() {
      return {
        bankPremiumslimitDialog: false,//默认隐藏 银保通出单保费限额维护修改弹框
        // 查询条件
        rules: {
          chdrcoy: [
            {max: 10, message: '长度在10个字符内', trigger: 'blur'},
            {validator: validRules.isEnglishOrNumber, trigger: 'blur'}
          ],
          branch: [
            {max: 10, message: '长度在10个字符内', trigger: 'blur'},
            {validator: validRules.isEnglishOrNumber, trigger: 'blur'}
          ],
          bankName: [
            {max: 20, message: '长度在20个字符内', trigger: 'blur'},
            {validator: validRules.isChineseOrEnglish, message: '请正确输入银行名称！', trigger: 'blur'}
          ],
        },
        searchParams: {
          chdrcoy: '',
          branch: '',
          bankName: '',
        },
        tableData: [], // 列表数据
        loading: false,
        paginations: { //需要给分页组件传的信息
          total: 0,      // 总数
          pageIndex: 1,  // 当前位于哪页
          pageSize: 10,  // 1页显示多少条
          pageSizes: [5, 10, 15, 20],  //每页显示多少条
          layout: "total, sizes, prev, pager, next, jumper"   // 翻页属性
        },

        /* 新增/修改/查看 弹框相关 */
        currentOperation: 'view', // 当前操作类型【new/edit/view】
        title_O: '新增银保通出单保费限额维护',
        oneDataRules: {
          chdrcoy: [
            {required: true, message: '请选择分公司', trigger: 'change'}
          ],
          branch: [
            {required: true, message: '请选择分支机构', trigger: 'change'}
          ],
          bankName: [
            {required: true, message: '请输入银行名称', trigger: 'blur'},
            {max: 20, message: '长度在20个字符内', trigger: 'blur'},
            {validator: validRules.isChineseOrEnglish, message: '请正确输入银行名称！', trigger: 'blur'}
          ],
          maxPremium: [
            {required: true, message: '请输入最高保费', trigger: 'blur'},
            {validator: validRules.isMoney_17_2, message: '请正确输入最高保额！', trigger: 'blur'}
          ]
        },
        oneData: { //弹框表单
          chdrcoy: '', // 分公司
          branch: '', // 分支机构
          bankName: '', // 银行名称
          maxPremium: '' // 最高保费
        },
        ssyMap: {}, // 分公司机构信息
        chdrcoyOptions: [], // 分公司下拉数据
        branchOptions: [], // 分支机构下拉数据
        branchOptions_D: [], // 分支机构下拉数据
      }
    },
    created() {
    },
    mounted() {
      getSsyOrgMap().then(data => {
        this.ssyMap = data;
        if (this.ssyMap) {
          this.chdrcoyOptions = [];
          this.branchOptions = [];
          for (const key in this.ssyMap) {
            const ssyorg = this.ssyMap[key];
            if (ssyorg) {
              if (ssyorg.slevel == 0 || ssyorg.slevel == 1) {
                this.chdrcoyOptions.push({value: ssyorg.sbusiorgid, label: ssyorg.sorgname});
              }
            }
          }
        }
      });
    },
    methods: {
      // 分公司值改变更新分支机构下拉数据
      getBranchOptions(chdrcoy) {
        this.branchOptions = [];
        this.searchParams.branch = '';
        if (chdrcoy) {
          const sorgid = this.ssyMap[chdrcoy].sorgid;
          const prefixSorgid = sorgid.substring(0, 3);
          for (const key in this.ssyMap) {
            const ssyorg = this.ssyMap[key];
            if (ssyorg) {
              if (prefixSorgid == ssyorg.sorgid.substring(0, 3)) {
                this.branchOptions.push({value: ssyorg.sbusiorgid, label: ssyorg.sorgname});
              }
            }
          }
        }
      },
      getBranchOptions_D(chdrcoy) {
        this.branchOptions_D = [];
        this.oneData.branch = '';
        if (chdrcoy) {
          const sorgid = this.ssyMap[chdrcoy].sorgid;
          const prefixSorgid = sorgid.substring(0, 3);
          for (const key in this.ssyMap) {
            const ssyorg = this.ssyMap[key];
            if (ssyorg) {
              if (prefixSorgid == ssyorg.sorgid.substring(0, 3)) {
                this.branchOptions_D.push({value: ssyorg.sbusiorgid, label: ssyorg.sorgname});
              }
            }
          }
        }
      },

      //表单格式化函数
      singleChanFormat(row) {//出单通道
        let resString = row.singleChan;
        const resArray = this.singleChanOptions.filter(item => {
          return item.value == resString;
        });
        if (resArray.length == 1) {
          resString = resArray[0].label;
        }
        return resString;
      },
      chdrcoyFormat(row) {//分公司
        let resString = row.chdrcoy;
        if (this.ssyMap && this.ssyMap[resString]) {
          resString = this.ssyMap[resString].sorgname;
        }
        return resString;
      },
      branchFormat(row) {//分支机构
        let resString = row.branch;
        if (this.ssyMap && this.ssyMap[resString]) {
          resString = this.ssyMap[resString].sorgname;
        }
        return resString;
      },

      // 导出
      exportData() {
        let para = {
          "chdrcoy": this.searchParams.chdrcoy,
          "branch": this.searchParams.branch,
          "bankName": this.searchParams.bankName,
          "pageSize": this.paginations.pageSize,
          "pageNumber": this.paginations.pageIndex,
        };
        this.$store.dispatch('loading/CHANGE_LOADING', true);
        queryListToExcel(para).then(res => {
          let blob = new Blob([res.data], { type: 'application/vnd.ms-excel;charset=utf-8' })
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(blob, 'bankfeemtc.xls');
          }
          let downloadElement = document.createElement('a');
          let href = window.URL.createObjectURL(blob); //创建下载的链接
          downloadElement.href = href;
          downloadElement.download = 'bankfeemtc.xls'; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href); //释放掉blob对象
          this.$store.dispatch('loading/CHANGE_LOADING', false);
        }).catch(err => {
          this.$store.dispatch('loading/CHANGE_LOADING', false);
          this.$message({
            type: 'error',
            message: '下载文件失败！'
          });
        });
      },

      // 查询列表
      getList() {
        console.log(this.ssyMap);
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            this.paginations.total = 0;
            this.tableData = [];
            let para = {
              "chdrcoy": this.searchParams.chdrcoy,
              "branch": this.searchParams.branch,
              "bankName": this.searchParams.bankName,
              "pageSize": this.paginations.pageSize,
              "pageNumber": this.paginations.pageIndex,
            };
            this.$store.dispatch('loading/CHANGE_LOADING', true);

            PAGE(para).then(res => {
              this.$store.dispatch('loading/CHANGE_LOADING', false);
              if (res.resultCode == constant.SUCCESS) {
                if (res.data && res.data.rows.length) {
                  this.paginations.total = res.data.total;
                  this.tableData = res.data.rows;
                } else {
                  this.$message({
                    message: '无符合条件任务！',
                    type: 'error'
                  });
                }
              }
            }).catch(err => {
              this.$store.dispatch('loading/CHANGE_LOADING', false);
            });
          }
        });
      },
      // 每页多少条切换
      handleSizeChange(pageSize) {
        this.paginations.pageSize = pageSize;
        this.paginations.pageIndex = 1;
        this.getList();
      },
      // 上下分页
      handleCurrentChange(page) {
        this.paginations.pageIndex = page;
        this.getList();
      },
      // 根据条件查询列表
      subGetList() {
        this.paginations.pageIndex = 1;
        this.getList();
      },
      // 清除查询条件
      resetSearch() {
        this.searchParams.chdrcoy = '';
        this.searchParams.branch = '';
        this.searchParams.bankName = '';
      },

      // 进入新增弹框
      toAddDialog() {
        this.currentOperation = 'new';
        this.title_O = '新增银保通出单保费限额维护';
        // 初始化弹框表单数据
        this.oneData = {
          chdrcoy: '', // 分公司
          branch: '', // 分支机构
          bankName: '', // 银行名称
          maxPremium: '' // 最高保费
        };
        this.bankPremiumslimitDialog = true;
      },
      // 进入修改弹框
      toEditDialog(item) {
        this.currentOperation = 'edit';
        this.title_O = '修改银保通出单保费限额维护';
        let item_t = {};
        for (const key in item) {
          item_t[key] = item[key];
        }
        this.oneData = item_t;
        const branch_T = this.oneData.branch;
        this.getBranchOptions_D(this.oneData.chdrcoy);
        this.oneData.branch = branch_T;
        this.bankPremiumslimitDialog = true;
      },
      // 进入查看弹框
      toViewDialog(item) {
        this.currentOperation = 'view';
        this.title_O = '查看银保通出单保费限额维护';
        this.oneData = item;
        const branch_T = this.oneData.branch;
        this.getBranchOptions_D(this.oneData.chdrcoy);
        this.oneData.branch = branch_T;
        this.bankPremiumslimitDialog = true;
      },
      // 关闭弹框
      dialogBack() {
        this.bankPremiumslimitDialog = false;
      },
      // 保存弹框数据
      saveData() {
        this.$refs['oneDataForm'].validate((valid) => {
          if (valid) {
            if (this.currentOperation == 'new') {
              this.$store.dispatch('loading/CHANGE_LOADING', true);
              ADD(this.oneData).then(res => {
                this.$store.dispatch('loading/CHANGE_LOADING', false);
                if (res.resultCode == constant.SUCCESS) {
                  this.bankPremiumslimitDialog = false;
                  this.$message({
                    type: 'success',
                    message: '新增成功！'
                  });
                  // 新增成功后，刷新列表
                  this.getList();
                }
              }).catch(err => {
                this.$store.dispatch('loading/CHANGE_LOADING', false);
              });
            } else if (this.currentOperation == 'edit') {
              this.$store.dispatch('loading/CHANGE_LOADING', true);
              UPDATE(this.oneData).then(res => {
                this.$store.dispatch('loading/CHANGE_LOADING', false);
                if (res.resultCode == constant.SUCCESS) {
                  this.bankPremiumslimitDialog = false;
                  this.$message({
                    type: 'success',
                    message: '修改成功！'
                  });
                  // 修改成功后，刷新列表
                  this.getList();
                }
              }).catch(err => {
                this.$store.dispatch('loading/CHANGE_LOADING', false);
              });
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },

      // 删除一条数据
      deleteData(item) {
        this.$confirm("确认删除？", '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('loading/CHANGE_LOADING', true)
          DELETE(item).then(res => {
            this.$store.dispatch('loading/CHANGE_LOADING', false)
            if (res.resultCode == constant.SUCCESS) {
              this.$message({
                type: 'success',
                message: '删除成功！'
              });
              this.paginations.pageIndex = 1;
              this.getList();
            }
          }).catch(err => {
            this.$store.dispatch('loading/CHANGE_LOADING', false);
          })
        });
      },
    },
    computed: {
      ...mapGetters(['tags']),
      reload() {
        return this.$store.state.loading.reload;
      }
    },
    activated() {
      if (this.reload) {
        this.$store.dispatch('loading/CHNAGE_RELOAD', false)
        Object.assign(this.$data, this.$options.data());
      }
    }
  }

</script>

<style lang="less" scoped>
  .fillcontain {
    padding-bottom: 0;
  }

  .contain {
    background: #fff;
    padding: 10px;
    margin-bottom: 20px;
  }

  .pagination {
    padding: 10px 20px;
    text-align: right;
  }

  .operationIcon {
    // padding: 12px;
    border: 1px solid #e5e5e5;
    border-radius: 50%;
    width: 22px;
    height: 22px;
    display: inline-block;
    cursor: pointer;
    box-shadow: 0 0 3px #f9f9f9;
  }

  .search_container {
    padding: 20px 20px 0 20px; //    border-top: 1px solid #e1e1e1;
  }

  .common-box {
    padding-bottom: 15px;
  }

  .common-lab {
    line-height: normal !important;
    text-align: right;

    .labelName {
      text-align: right;
    }
  }
</style>